<template>
	<div
		class="sub-table-box"
		:class="[config.type]"
	>
		<div
			v-if="config.showTitle && config.label"
			class="global-common-title"
		>
			<span
				v-if="config.tipLabel"
				slot="label"
			>{{config.label}}
				<Tooltip
					placement="top"
					:content="config.tipLabel"
				>
					<a class="el-icon-question global-tooltip-question"/>
				</Tooltip>
			</span>
			<h2 v-else>{{config.label}}</h2>
		</div>
		<Table
			ref="formTable"
			:data="tableFormData"
			v-bind="config.tableConf || {}"
			:show-summary="config['show-summary']"
			:summary-method="getTableSummaries"
			size="mini"
			@cell-click="focusInput"
		>
			<TableColumn
				width="50"
				align="center"
				label="序号"
			>
				<!-- 序号 -->
				<template #default="scope">
					<div class="row-action">
						<span
							class="index"
							:class="{ 'btn-disabled': disabled }"
						>
							{{scope.$index + 1}}</span>
						<i
							class="el-icon-delete delete-btn"
							@click="removeRow(scope.$index)"
						/>
					</div>
				</template>
			</TableColumn>
			<!-- 组件列 -->
			<template v-for="(head, cIndex) in tableData">
				<TableColumn
					v-if="
						!head.hidden &&
							(!head.config.visibility ||
								(Array.isArray(head.config.visibility) &&
									head.config.visibility.includes('pc')))
					"
					:key="head.config.formId"
					:min-width="head['min-width']"
					:prop="head.model"
					:width="head.config.columnWidth"
				>
					<template #header>
						<span
							v-if="head.config.required"
							style="color: #f56c6c"
						>*</span>
						<span
							v-if="head.config.tipLabel && head.config.label"
							slot="label"
						>{{head.config["label"]}}
							<Tooltip
								placement="top"
								:content="head.config.tipLabel"
							>
								<a class="el-icon-question global-tooltip-question"/>
							</Tooltip>
						</span>
						<span v-if="head && head.config && !head.config['tipLabel']">
							{{head.config['label']}}
						</span>
					</template>
					<template #default="scope">
						<!-- 单选框组 多选框组 都替换成下拉 并添加options -->
						<template
							v-if="['select', 'checkbox', 'radio'].includes(head.config.identity)"
						>
							<McSelect
								v-model="tableFormData[scope.$index][cIndex].value"
								filterable
								v-bind="getConfById(head.config.formId, scope.$index)"
								:row-index="scope.$index"
								:options="tableFormData[scope.$index][cIndex].options"
								@blur="onFormBlur(scope.$index, cIndex, 'el-select')"
								@change="
									onFormDataChange(scope.$index, cIndex, 'el-select', arguments)
								"
							/>
						</template>
						<!-- 单行输入 -->
						<template v-else-if="head.config.identity === 'comInput'">
							<McInput
								v-model="tableFormData[scope.$index][cIndex].value"
								v-bind="getConfById(head.config.formId, scope.$index)"
								:row-index="scope.$index"
								@blur="onFormBlur(scope.$index, cIndex, 'el-input')"
								@change="
									onFormDataChange(scope.$index, cIndex, 'el-input', arguments)
								"
							>
								<template v-if="head.customSlot">
									<template
										v-if="head.customSlot.prepend"
										slot="prepend"
									>
										{{head.customSlot.prepend}}
									</template>
									<template
										v-if="head.customSlot.append"
										slot="append"
									>
										{{head.customSlot.append}}
									</template>
								</template>
							</McInput>
						</template>
						<!-- 下拉树形 -->
						<template v-else-if="head.config.identity === 'treeSelect'">
							<McTreeSelect
								v-model="tableFormData[scope.$index][cIndex].value"
								:options="tableFormData[scope.$index][cIndex].options"
								:props="head.props.props"
								:placeholder="head.placeholder"
								:clearable="head.clearable"
								:multiple="head.multiple"
								:filterable="head.filterable"
								:disabled="head.disabled"
							/>
						</template>
						<!-- 级联选择 -->
						<template v-else-if="head.config.identity === 'cascader'">
							<Cascader
								v-model="tableFormData[scope.$index][cIndex].value"
								:options="tableFormData[scope.$index][cIndex].options"
								:props="head.props.props"
								:placeholder="head.placeholder"
								:clearable="head.clearable"
								:show-all-levels="head['show-all-levels']"
								:separator="head.separator"
								:filterable="head.filterable"
								:disabled="head.disabled"
							/>
						</template>
						<!-- 其他 -->
						<component
							:is="head.config.tag"
							v-else
							v-model="tableFormData[scope.$index][cIndex].value"
							:row-index="scope.$index"
							:table-v-model="config.model"
							:component-v-model="head.model"
							v-bind="getConfById(head.config.formId, scope.$index)"
							:form-data="formData"
							@blur="onFormBlur(scope.$index, cIndex, head.config.tag)"
							@change="
								onFormDataChange(scope.$index, cIndex, head.config.tag, arguments)
							"
						/>
						<div
							v-show="!tableFormData[scope.$index][cIndex].valid"
							class="error-tip"
						>
							不能为空
						</div>
						<div
							v-show="
								tableFormData[scope.$index][cIndex].valid &&
									!tableFormData[scope.$index][cIndex].regValid
							"
							class="error-tip"
						>
							{{tableFormData[scope.$index][cIndex].regErrorText}}
						</div>
					</template>
				</TableColumn>
			</template>
		</Table>
		<div
			v-if="!disabled"
			class="global-table-actions"
			@click="addItem()"
		>
			<Button
				type="text"
				icon="el-icon-plus"
			>
				{{config.actionText}}
			</Button>
		</div>
		<SelectDialog
			v-if="selectDialogVisible"
			ref="selectDialog"
			:config="config.addTableConf"
			:form-data="formData"
			@select="addForSelect"
		/>
	</div>
</template>
<script>
import McTreeSelect from '../tree-select/index.vue';
import McInput from '../input/index.vue';
const dyOptionsList = ['radio', 'checkbox', 'select', 'cascader', 'treeSelect'];
import SelectDialog from './SelectDialog.vue';
import {thousandsFormat,EventBus,getScriptFunc} from '../../utils';
import {magic} from '@lexmis/magic-ui/pc';
import {Table,TableColumn,Cascader,Button,Tooltip } from 'element-ui'
import McSelect from '../select/index.vue';
export default {
	name:'McSubTable',
	components:{McSelect, McTreeSelect,Button,Tooltip,Cascader, SelectDialog,Table,TableColumn,McInput},
	inject:['parameter'],
	props:{
		config:{
			type:Object,
			default: () => {},
		},
		value:{
			type:Array,
			default: () => [],
		},
		formData:Object,
		relations:Object,
		model:String,
		disabled:{
			type:Boolean,
			default:false,
		},
	},
	data(){
		return {
			tableFormData:[],
			tableData:[],
			activeRowIndex:0,
			selectDialogVisible:false,
			relationForm:{},
			isAddRow:true, // list类型下 添加行数据 number类型组件会进行校验 产生不需要的结果 在这里进行添加行数据判断 hack
		};
	},
	computed:{
		childRelations(){
			const obj = {};
			for(const key in this.relations){
				if(key.includes('-')){
					const tableVModel = key.split('-')[0];
					if(tableVModel === this.model){
						const newKey = key.split('-')[1];
						obj[newKey] = this.relations[key];
					}
				}
			}
			return obj;
		},
	},
	created(){
		this.tableData = this.config.children;
		this.buildOptions();
		if(this.value && this.value.length){
			this.value.forEach((t) => this.addRow(t));
		}else{
            // this.addRow()
		}
	},
	mounted(){
		EventBus.$on('trigger-relation-formattr', this.handleRelationFormAttr);
	},
	beforeUnmount(){
		EventBus.$off('trigger-relation-formattr', this.handleRelationFormAttr);
	},
	methods:{
		handleRelationFormAttr(payload){
			if(Object.prototype.toString.call(payload) === '[object Object]'){
				this.relationForm = payload;
				for(const item of this.tableFormData){
					const ids = item.map((i) => i.value);
					if(ids.includes(payload.F_ID)){
						for(const item2 of item){
							if(item2.tag === 'mc-relation-formattr'){
								this.$set(item2, 'value', this.relationForm[item2.config.showField]);
							}
						}
					}
				}
			}
		},
		buildOptions(){
			this.tableData.forEach((cur) => {
				const config = cur.config;
				if(dyOptionsList.indexOf(config.identity) > -1){
                    // const isTreeSelect =
                    //     config.identity === "treeSelect" || config.identity === "cascader";
					if(config.dataType === 'dictionary'){
						if(!config.dictionaryType) return;
						magic.core
							.service({
								url:'/api/magic-dict/getDictItemByDictIdList',
								method:'post',
								data:{
									dictId:config.dictionaryType,
								},
							})
							.then((res) => {
								cur.options = res.data.list;
								this.innerOptions = res.data.map((item) => ({
									...item,
									fullName:item.name,
								}));
							});
                        // getDictionaryDataSelector(config.dictionaryType).then(res => {
                        //     cur.options = res.data.list;
                        // });
					}
					if(config.dataType === 'dynamic'){
						if(!config.propsUrl) return;
                        // const query = {
                        //     paramList: config.templateJson
                        //         ? this.getDefaultParamList(config.templateJson, this.formData)
                        //         : [],
                        // };
                        // getDataInterfaceRes(config.propsUrl, query).then(res => {
                        //     const realData = res.data;
                        //     if (Array.isArray(realData)) {
                        //         cur.options = realData;
                        //     } else {
                        //         cur.options = [];
                        //     }
                        // });
					}
				}
			});
		},
		handleRelationForParent(e, defaultValue, notSetDefault){
			if(!this.tableFormData.length) return;
			for(let i = 0; i < this.tableFormData.length; i++){
				const row = this.tableFormData[i];
				for(let j = 0; j < row.length; j++){
					const item = row[j];
					const model
                        = item.identity === 'popupSelect'
                        	? item.model.substring(0, item.model.indexOf('_relation_'))
                        	: item.model;
					if(e.model === model){
						if(!notSetDefault) item.value = defaultValue;
						if(e.opType === 'setOptions'){
							item.options = [];
                            // const query = {
                            //     paramList: this.getParamList(
                            //         e.config.templateJson,
                            //         this.formData,
                            //         i,
                            //     ),
                            // };
                            // getDataInterfaceRes(e.config.propsUrl, query).then(res => {
                            //     const realData = res.data;
                            //     item.options = Array.isArray(realData) ? realData : [];
                            // });
						}
						if(e.opType === 'setUserOptions'){
							const value = this.formData[e.relationField] || [];
							item.config.ableRelationIds = Array.isArray(value) ? value : [value];
						}
						if(e.opType === 'setDate'){
							let startTime = 0;
							let endTime = 0;
							if(e.config.startRelationField && e.config.startTimeType == 2){
								startTime = this.formData[e.config.startRelationField] || 0;
							}else{
								startTime = e.startTime;
							}
							if(e.config.endRelationField && e.config.endTimeType == 2){
								endTime = this.formData[e.config.endRelationField] || 0;
							}else{
								endTime = e.endTime;
							}
							item.config.startTime = startTime;
							item.config.endTime = endTime;
						}
						if(e.opType === 'setTime'){
							let startTime = '';
							let endTime = '';
							if(e.config.startRelationField && e.config.startTimeType == 2){
								startTime
                                    = this.formData[e.config.startRelationField] || '00:00:00';
								startTime = startTime + ':00';
								if(startTime.split(':').length == 3){
									startTime = startTime;
								}else{
									startTime = startTime + ':00';
								}
							}else{
								startTime = e.startTime || '00:00:00';
							}
							if(e.config.endRelationField && e.config.endTimeType == 2){
								endTime = this.formData[e.config.endRelationField] || '23:59:59';
								if(endTime.split(':').length == 3){
									endTime = endTime;
								}else{
									endTime = endTime + ':00';
								}
							}else{
								endTime = e.endTime || '23:59:59';
							}
							item.config.startTime = startTime;
							item.config.endTime = endTime;
						}
					}
				}
			}
			this.updateParentData();
		},
		handleRelation(data, rowIndex){
			const currRelations = this.childRelations;
			for(const key in currRelations){
				if(key === data.model){
					for(let i = 0; i < currRelations[key].length; i++){
						const e = currRelations[key][i];
						const config = e.config;
						const identity = config.identity;
						let defaultValue = null;
						if(
							['checkbox', 'cascader'].includes(identity)
							|| ([
								'select',
								'treeSelect',
								'popupSelect',
								'popupTableSelect',
								'userSelect',
							].includes(identity)
							&& e.multiple)
						){
							defaultValue = [];
						}
						const row = this.tableFormData[rowIndex];
						for(let j = 0; j < row.length; j++){
							const item = row[j];
							const model
                                = item.identity === 'popupSelect'
                                	? item.model.substring(
                                		0,
                                		item.model.indexOf('_relation_'),
                                	)
                                	: item.model;
							if(e.model === model){
								if(e.opType === 'setOptions'){
									item.options = [];
                                    // const query = {
                                    //     paramList: this.getParamList(
                                    //         e.config.templateJson,
                                    //         this.formData,
                                    //         rowIndex,
                                    //     ),
                                    // };
                                    // getDataInterfaceRes(e.config.propsUrl, query).then(res => {
                                    //     const realData = res.data;
                                    //     item.options = Array.isArray(realData) ? realData : [];
                                    // });
								}
								if(e.opType === 'setUserOptions'){
									const value = this.getFieldVal(e.relationField, rowIndex) || [];
									item.config.ableRelationIds = Array.isArray(value)
										? value
										: [value];
								}
								if(e.opType === 'setDate'){
									let startTime = 0;
									let endTime = 0;
									if(
										e.config.startRelationField
										&& e.config.startTimeType == 2
									){
										startTime
                                            = this.getFieldVal(
												e.config.startRelationField,
												rowIndex,
											) || 0;
									}else{
										startTime = e.startTime;
									}
									if(e.config.endRelationField && e.config.endTimeType == 2){
										endTime
                                            = this.getFieldVal(e.config.endRelationField, rowIndex)
                                            || 0;
									}else{
										endTime = e.endTime;
									}
									item.config.startTime = startTime;
									item.config.endTime = endTime;
								}
								if(e.opType === 'setTime'){
									let startTime = 0;
									let endTime = 0;
									if(
										e.config.startRelationField
										&& e.config.startTimeType == 2
									){
										startTime
                                            = this.getFieldVal(
												e.config.startRelationField,
												rowIndex,
											) || '00:00:00';
										if(startTime.split(':').length == 3){
											startTime = startTime;
										}else{
											startTime = startTime + ':00';
										}
									}else{
										startTime = e.startTime;
									}
									if(e.config.endRelationField && e.config.endTimeType == 2){
										endTime
                                            = this.getFieldVal(e.config.endRelationField, rowIndex)
                                            || '23:59:59';
										if(endTime.split(':').length == 3){
											endTime = endTime;
										}else{
											endTime = endTime + ':00';
										}
									}else{
										endTime = e.endTime;
									}
									item.config.startTime = startTime;
									item.config.endTime = endTime;
								}
								if(item.value != defaultValue){
									item.value = defaultValue;
									this.$nextTick(() => this.handleRelation(item, rowIndex));
								}
							}
						}
					}
				}
			}
			this.updateParentData();
		},
		buildRowAttr(rowIndex){
			const row = this.tableFormData[rowIndex];
			for(let i = 0; i < row.length; i++){
				const item = row[i];
				const cur = row[i].config;
				const config = cur.config;
				for(const key in this.value[rowIndex]){
					if(key === item.model){
						item.value = this.value[rowIndex][key];
					}
				}
				if(dyOptionsList.indexOf(config.identity) > -1){
					if(config.dataType === 'dynamic'){
						if(
							!config.propsUrl
							|| !config.templateJson
							|| !config.templateJson.length
						){
							return;
						}
                        // const query = {
                        //     paramList: config.templateJson
                        //         ? this.getParamList(config.templateJson, this.formData, rowIndex)
                        //         : [],
                        // };
                        // getDataInterfaceRes(config.propsUrl, query).then(res => {
                        //     const realData = res.data;
                        //     item.options = Array.isArray(realData) ? realData : [];
                        // });
					}
				}
				if(
					config.identity === 'userSelect'
					&& cur.relationField
					&& cur.selectType !== 'all'
					&& cur.selectType !== 'custom'
				){
					const value = this.getFieldVal(cur.relationField, rowIndex) || [];
					cur.ableRelationIds = Array.isArray(value) ? value : [value];
				}
				if(config.identity === 'date'){
					let startTime = 0;
					let endTime = 0;
					if(cur.config.startRelationField && cur.config.startTimeType == 2){
						startTime = this.getFieldVal(cur.config.startRelationField, rowIndex) || 0;
					}else{
						startTime = cur.startTime;
					}
					if(cur.config.endRelationField && cur.config.endTimeType == 2){
						endTime = this.getFieldVal(cur.config.endRelationField, rowIndex) || 0;
					}else{
						endTime = cur.endTime;
					}
					item.config.startTime = startTime;
					item.config.endTime = endTime;
				}
				if(config.identity === 'time'){
					let startTime = 0;
					let endTime = 0;
					if(cur.config.startRelationField && cur.config.startTimeType == 2){
						startTime
                            = this.getFieldVal(cur.config.startRelationField, rowIndex) || '00:00:00';
						if(startTime && startTime.split(':').length == 3){
							startTime = startTime;
						}else{
							startTime = startTime + ':00';
						}
					}else{
						startTime = cur.startTime;
					}
					if(cur.config.endRelationField && cur.config.endTimeType == 2){
						endTime
                            = this.getFieldVal(cur.config.endRelationField, rowIndex) || '23:59:59';
						if(startTime.split(':').length == 3){
							endTime = endTime;
						}else{
							endTime = endTime + ':00';
						}
					}else{
						endTime = cur.endTime;
					}
					item.config.startTime = startTime;
					item.config.endTime = endTime;
				}
			}
		},
		getParamList(templateJson, formData, index){
			for(let i = 0; i < templateJson.length; i++){
				if(templateJson[i].relationField){
					if(templateJson[i].relationField.includes('-')){
						const childVModel = templateJson[i].relationField.split('-')[1];
						const list = this.tableFormData[index].filter(
							(o) => o.model === childVModel,
						);
						if(!list.length){
							templateJson[i].defaultValue = '';
						}else{
							const item = list[0];
							templateJson[i].defaultValue = item.value;
						}
					}else{
						templateJson[i].defaultValue
                            = formData[templateJson[i].relationField] || '';
					}
				}
			}
			return templateJson;
		},
		getDefaultParamList(templateJson, formData){
			for(let i = 0; i < templateJson.length; i++){
				if(templateJson[i].relationField){
					if(templateJson[i].relationField.includes('-')){
						const childVModel = templateJson[i].relationField.split('-')[1];
						const list = this.tableData.filter((o) => o.model === childVModel);
						templateJson[i].defaultValue = '';
						if(list.length) templateJson[i].defaultValue = list[0].config.defaultValue;
					}else{
						templateJson[i].defaultValue
                            = formData[templateJson[i].relationField] || '';
					}
				}
			}
			return templateJson;
		},
		getFieldVal(field, rowIndex){
			let val = '';
			if(field.includes('-')){
				const childVModel = field.split('-')[1];
				const list = this.tableFormData[rowIndex].filter((o) => o.model === childVModel);
				if(!list.length){
					val = '';
				}else{
					const item = list[0];
					val = item.value;
				}
			}else{
				val = this.formData[field] || '';
			}
			return val;
		},
		clearAddRowFlag(){
			this.$nextTick(() => {
				this.isAddRow = false;
			});
		},
        /**
         * @event cell-click Table 单元格点击事件
         * 点击单元格 聚焦单元格中的input
         */
		focusInput(row, column, cell, event){
			const child = cell.querySelector('.cell').firstElementChild;
			const input = child && child.querySelector('input');
			input && input.focus();
		},
		setTableFormData(prop, value){
			const activeRow = this.tableFormData[this.activeRowIndex];
			for(let i = 0; i < activeRow.length; i++){
				let model = activeRow[i].model;
				if(activeRow[i].model.indexOf('_relation_') >= 0){
					model = activeRow[i].model.substring(
						0,
						activeRow[i].model.indexOf('_relation_'),
					);
				}
				if(model === prop){
					activeRow[i].value = value;
					this.handleRelation(activeRow[i], this.activeRowIndex);
					break;
				}
			}
		},
		getTableFieldOptions(prop){
			let res = [];
			for(let i = 0; i < this.tableData.length; i++){
				if(this.tableData[i].model === prop){
					const item = this.tableData[i];
					res = item.options || [];
					break;
				}
			}
			return res;
		},
		setTableShowOrHide(prop, value){
			for(let i = 0; i < this.tableData.length; i++){
				if(this.tableData[i].model === prop){
					this.tableData[i].hidden = value;
					break;
				}
			}
		},
		onFormBlur(rowIndex, colIndex, tag){
			const data = this.tableFormData[rowIndex][colIndex];
			if(data && data.on && data.on.blur){
				const func = getScriptFunc.call(this, data.on.blur);
				if(!func) return;
				func.call(this, {
					data:null,
					...this.parameter,
				});
			}
		},
		onFormDataChange(rowIndex, colIndex, tag, params){
			if(this.isAddRow) return;
			const data = this.tableFormData[rowIndex][colIndex];
			this.activeRowIndex = rowIndex;
			if(data && data.on && data.on.change){
				const func = getScriptFunc.call(this, data.on.change);
				if(!func) return;
				let value = '';
				if(['select', 'radio', 'checkbox'].includes(data.identity)){
					const options = data.options;
					if(data.config.multiple || data.identity === 'checkbox'){
						const _value = [];
						for(let i = 0; i < params[0].length; i++){
							inner: for(let j = 0; j < options.length; j++){
								if(params[0][i] === options[j][data.config.props.props.value]){
									_value.push(options[j]);
									break inner;
								}
							}
						}
						value = _value;
					}else{
						let _value = {};
						for(let i = 0; i < options.length; i++){
							if(params[0] === options[i][data.config.props.props.value]){
								_value = options[i];
								break;
							}
						}
						value = _value;
					}
				}else if(data.identity === 'numInput'){
					value = params[0];
				}else{
					value = params.length > 1 ? params[1] : params[0];
				}
				func.call(this, {
					data:value,
					...this.parameter,
				});
			}
			data.required && (data.valid = this.checkData(data));
			data.regList && data.regList.length && (data.regValid = this.checkRegData(data));
            // if (['el-input-number', 'calculate'].includes(tag)) this.updateParentData()
			this.updateParentData();
			this.handleRelation(data, rowIndex);
		},
        /**
         * 校验单个表单数据
         * @param {CmpConfig} 组件配置对象
         */
		checkData({tag, value}){
			if([null, undefined, ''].includes(value)) return false;
            // if (tag === 'org-select') return this.checkOrgData(value)
			if(Array.isArray(value)) return value.length > 0;
			return true;
		},
        /**
         * 对组织机构部门控数据单独校验
         */
		checkOrgData(data){
			const isArray = Array.isArray;
			if(typeof data !== 'object' || isArray(data)) return false;
			let count = 0;
			for(const key in data){
				count += isArray(data[key]) ? data[key].length : 0;
			}
			return count > 0;
		},
		checkRegData(col){
			let res = true;
			for(let i = 0; i < col.regList.length; i++){
				const item = col.regList[i];
				if(item.pattern){
					const pattern = eval(item.pattern);
					if(col.value && !pattern.test(col.value)){
						res = false;
						col.regErrorText = item.message;
						break;
					}
				}
			}
			return res;
		},
        /**
         * 校验表格数据必填项
         */
		submit(){
			let res = true;
			const checkCol = (col) => {
				col.required && !this.checkData(col) && (res = col.valid = false);
				col.regList
				&& col.regList.length
				&& !this.checkRegData(col)
				&& (res = col.regValid = false);
			};
			this.tableFormData.forEach((row) => row.forEach(checkCol));
			return res ? this.getTableValue() : false;
		},
        /**
         * 根据formId获取完整组件配置
         */
		getConfById(formId, rowIndex){
			const item = this.tableFormData[rowIndex].find((t) => t.formId === formId).config;
			const itemConfig = item.config;
			const newObj = {};
			for(const key in item){
				if(!['config', 'slot', 'model', 'props', 'on'].includes(key)){
					newObj[key] = item[key];
				}
				if(key === 'props'){
					newObj[key] = item[key][key];
				}
				if(key === 'disabled'){
					newObj[key] = this.disabled || item[key];
				}
			}
			if(['relationForm', 'popupSelect'].includes(itemConfig.identity)){
				newObj['field'] = item.model + '_relation_' + rowIndex;
				newObj.config = itemConfig;
			}
			if(['relationFormAttr', 'popupAttr'].includes(itemConfig.identity)){
				const prop = newObj['relationField'].split('_table_')[0];
				newObj['relationField'] = prop + '_relation_' + rowIndex;
				newObj['isStorage'] = itemConfig.isStorage;
			}
			return newObj;
		},
        /**
         * 获取默认行数据
         */
		getEmptyRow(val, rowIndex){
			return this.tableData.map((t, index) => {
				let options = [];
				if(dyOptionsList.indexOf(t.config.identity) > -1){
					options = t.options;
				}
				if(t.config.identity === 'date' && t.config.defaultCurrent){
					const format = t.format;
					const dateStr = this.$commonUtils.toDate(new Date().getTime(), format);
					const time
                        = format === 'yyyy'
                        	? '-01-01 00:00:00'
                        	: format === 'yyyy-MM'
                        		? '-01 00:00:00'
                        		: format === 'yyyy-MM-dd'
                        			? ' 00:00:00'
                        			: '';
					t.config.defaultValue = new Date(dateStr + time).getTime();
				}
				if(t.config.identity === 'time' && t.config.defaultCurrent){
					t.config.defaultValue = this.$commonUtils.toDate(new Date(), t.format);
				}
				const res = {
					tag:t.config.tag,
					formId:t.config.formId,
					value:(val && val[t.model]) || t.config.defaultValue,
					options,
					valid:true,
					regValid:true,
					regErrorText:'',
					on:t.on || {},
					identity:t.config.identity,
					model:['relationForm', 'popupSelect'].includes(t.config.identity)
						? t.model + '_relation_' + rowIndex
						: t.model,
					regList:t.config.regList || [],
					required:t.required,
					rowData:val || {},
					config:t,
				};
				return res;
			});
		},
        // 获取表格数据
		getTableValue(){
			return this.tableFormData.map((row) =>
				row.reduce((p, c) => {
					let str = c.model;
					if(c.model && c.model.indexOf('_relation_') >= 0){
						str = c.model.substring(0, c.model.indexOf('_relation_'));
					}
					p[str] = c.value;
					if(c.rowData) p = {...c.rowData, ...p};
					return p;
				}, {}),
			);
		},
        // 更新父级数据 触发计算公式更新
		updateParentData(){
			const newVal = this.getTableValue();
			this.$emit('input', newVal);
		},
		removeRow(index){
			this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
				type:'warning',
			})
				.then(() => {
					this.tableFormData.splice(index, 1);
					this.updateParentData();
				})
				.catch(() => {});
		},
		addRow(val){
			this.isAddRow = true;
			if(!Array.isArray(this.tableFormData))this.tableFormData = [];
			const rowIndex = this.tableFormData.length;
			this.tableFormData.push(JSON.parse(JSON.stringify(this.getEmptyRow(val, rowIndex))));
			this.buildRowAttr(rowIndex);
			this.clearAddRowFlag();
			this.updateParentData();
		},
		addItem(){
			if(this.config.addType == 1){
				this.openSelectDialog();
			}else{
				this.addRow();
			}
		},
		openSelectDialog(){
			this.selectDialogVisible = true;
			this.$nextTick(() => {
				this.$refs.selectDialog.init();
			});
		},
		addForSelect(data){
			data.forEach((t) => this.addRow(t));
		},
		getCmpValOfRow(row, key){
            // 获取数字相关组件的输入值
            // const isNumCmp = tag => ['fc-amount', 'el-input-number', 'el-slider'].includes(tag)
			if(!this.config.summaryField.length) return NaN;
			const isSummary = (key) => this.config.summaryField.includes(key);
			const target = row.find((t) => t.model === key);
			if(!target) return NaN;
			const data = isNaN(target.value) ? 0 : Number(target.value);
			if(isSummary(key)) return data || 0;
			return NaN;
		},
        /**
         * 对表格进行合计 目前只支持数字，金额，滑块
         */
		getTableSummaries(param){
			const {columns, data} = param;
			const sums = [];
			const thousandsField = [];
			const tableData = this.tableData.filter((o) => !o.hidden);
			tableData.forEach((res) => {
				if(res.thousands) thousandsField.push(res.model);
			});
			if(tableData.length + 1 !== columns.length) return []; // 防止多次加载
			columns.forEach((column, index) => {
				if(index === 0){
					sums[index] = '合计';
					return;
				}
				const sumVal = data.reduce(
					(sum, d) => sum + this.getCmpValOfRow(d, column.property),
					0,
				);
				sums[index] = Number.isNaN(sumVal) ? '' : sumVal;
				if(sums[index] && !Number.isInteger(sums[index])){
					sums[index] = sums[index].toFixed(2);
				}
				if(thousandsField.includes(column.property)){
					sums[index] = thousandsFormat(sums[index]);
				}
			});
			return sums;
		},
		resetTable(){
			this.tableData = this.config.children;
			this.tableFormData = [];
            // this.addRow()
		},
		reset(){
			this.tableData.map((t) => {
				const index = this.tableFormData[0].findIndex((c) => c.model === t.model);
				if(index === -1) return;
				for(let i = 0; i < this.tableFormData.length; i++){
					this.tableFormData[i][index].value = t.defaultValue;
				}
			});
		},
	},
};
</script>
<style lang="scss" scoped>
.sub-table-box {
    margin-bottom: 0px;
    width: 100%;
    .row-action {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 32px;

        .el-icon-delete {
            position: absolute;
            opacity: 0;
            z-index: -1;
            transform: translate(-50%, -50%);
            cursor: pointer;
            line-height: 3px;
            margin-left: 10px;
        }
    }
    .actions {
        text-align: center;
        border: 1px solid #ebeef5;
        border-top: none;
        .list-summary {
            line-height: 24px;
            overflow: hidden;
            border: 1px solid #e5e5e5;
            border-top: none;
        }
    }

    &.list {
        .list-row {
            padding: 18px 0 10px;
            text-align: left;
            border-bottom: 1px solid #e5e5e5;
            position: relative;
            &:hover .delete-btn {
                display: block;
            }
            .delete-btn {
                position: absolute;
                right: 10px;
                top: 20px;
                z-index: 999;
                cursor: pointer;
                display: none;
                &:hover {
                    color: #000;
                }
            }
            .row-item {
                margin-bottom: 18px;
                position: relative;
                &.error {
                    .error-tip {
                        top: 74%;
                        z-index: 1;
                    }
                    ::v-deep .el-input__inner {
                        border-color: #f56c6c;
                    }
                }
                > div {
                    &:first-child {
                        text-align: right;
                        vertical-align: middle;
                        float: left;
                        font-size: 14px;
                        color: #606266;
                        line-height: 32px;
                        padding: 0 12px 0 0;
                        box-sizing: border-box;
                    }
                }
            }
        }
        .error-tip {
            font-size: 12px;
            padding-left: 6px;
            color: #f56c6c;
            position: absolute;
            left: 100px;
            top: 0;
            z-index: -1;
            transition: bottom 0.3s;
            min-height: auto;
        }
    }
}

.sub-table-box.table {
    // 索引和删除按钮切换
    ::v-deep .el-table__row:hover {
        .index {
            display: none;
            &.btn-disabled {
                display: block;
                & + .el-icon-delete {
                    opacity: 0;
                    z-index: -1;
                }
            }
        }
        .el-icon-delete {
            z-index: 9;
            opacity: 1;
        }
    }
    ::v-deep .el-input-number {
        width: 100%;
        min-width: 120px;
    }
    ::v-deep .el-table__header th {
        line-height: 1;
    }

    ::v-deep .el-table .el-table__body {
        td {
            padding: 2px 0;
            background: #fff !important;
            vertical-align: top;
            .error-tip {
                font-size: 12px;
                padding-left: 6px;
                color: #f56c6c;
            }
            .cell {
                position: relative;
            }
        }

        td:not(:first-child) {
            // vertical-align: top;
            &::after,
            &::before {
                content: "";
                width: 10px;
                height: 10px;
                background: white;
                position: absolute;
                border: 2px solid transparent;
                transition: border-color 0.3s;
            }

            &::after {
                border-top: none;
                border-right: none;
                left: 0;
                bottom: 0;
            }

            &::before {
                border-bottom: none;
                border-left: none;
                right: 0;
                top: 0;
            }

            &:hover {
                &::after,
                &::before {
                    border-color: red;
                }
            }
        }
    }
}
</style>